<script setup lang="ts">
import type { PropType } from 'vue';

import type { DeptTree } from '#/api/system/user/model';

import { h, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  SyncOutlined,
} from '@ant-design/icons-vue';
import { Empty, Popconfirm, Skeleton, Tree } from 'ant-design-vue';

import { delGroup, groupTree } from '#/api/iot/device/group';

import addGroupModal from './add-group-modal.vue';

defineOptions({ inheritAttrs: false });

withDefaults(defineProps<{ showSearch?: boolean }>(), { showSearch: true });

const emit = defineEmits<{
  /**
   * 点击刷新按钮的事件
   */
  reload: [];
  /**
   * 点击节点的事件
   */
  select: [];
}>();

const selectDeptId = defineModel('selectDeptId', {
  required: true,
  type: Array as PropType<string[]>,
});

const searchValue = defineModel('searchValue', {
  type: String,
  default: '',
});

/** 部门数据源 */
type DeptTreeArray = DeptTree[];
const deptTreeArray = ref<DeptTreeArray>([]);
/** 骨架屏加载 */
const showTreeSkeleton = ref<boolean>(true);

const [AddGroupModal, addGroupModalApi] = useVbenModal({
  connectedComponent: addGroupModal,
});

function addRootGroup(id: number | string) {
  addGroupModalApi.setData({ id, type: 'addRoot' });
  addGroupModalApi.open();
}

function addSonGroup(id: string) {
  addGroupModalApi.setData({ id, type: 'addSub' });
  addGroupModalApi.open();
}

function editGroup(id: string, parentId: string) {
  addGroupModalApi.setData({ id, parentId, type: 'edit' });
  addGroupModalApi.open();
}

async function handleDelGroup(id: string) {
  await delGroup(id);
  loadTree();
}

async function loadTree() {
  showTreeSkeleton.value = true;
  searchValue.value = '';
  selectDeptId.value = [];

  const ret = await groupTree();
  console.log(ret);

  deptTreeArray.value = ret;
  showTreeSkeleton.value = false;
}

onMounted(loadTree);
</script>

<template>
  <div :class="$attrs.class">
    <Skeleton
      :loading="showTreeSkeleton"
      :paragraph="{ rows: 8 }"
      active
      class="p-[8px]"
    >
      <div
        class="bg-background flex h-full flex-col overflow-y-auto rounded-lg"
      >
        <!-- 固定在顶部 必须加上bg-background背景色 否则会产生'穿透'效果 -->
        <div
          v-if="showSearch"
          class="bg-background z-100 sticky left-0 top-0 flex justify-between p-[8px]"
        >
          <a-button
            v-access:code="['iot:deviceGroup:add']"
            size="small"
            :icon="h(PlusOutlined)"
            @click="addRootGroup(0)"
          >
            添加根分组
          </a-button>
          <a-button size="small" :icon="h(SyncOutlined)" @click="loadTree">
            刷新
          </a-button>
        </div>
        <div class="h-full overflow-x-hidden px-[8px]">
          <Tree
            v-bind="$attrs"
            v-if="deptTreeArray.length > 0"
            v-model:selected-keys="selectDeptId"
            :class="$attrs.class"
            :field-names="{ title: 'label', key: 'id' }"
            :tree-data="deptTreeArray"
            :virtual="false"
            default-expand-all
            @select="emit('select')"
          >
            <template #title="{ label, id, parentId }">
              <div class="flex justify-between">
                <div>{{ label }}</div>
                <div>
                  <PlusOutlined
                    class="mr-1"
                    @click.stop="addSonGroup(id)"
                    v-access:code="['iot:deviceGroup:add']"
                  />
                  <EditOutlined
                    v-access:code="['iot:deviceGroup:edit']"
                    class="mr-1"
                    @click.stop="editGroup(id, parentId)"
                  />
                  <Popconfirm
                    placement="rightTop"
                    title="是否要删除数据？"
                    @confirm="handleDelGroup(id)"
                  >
                    <DeleteOutlined
                      v-access:code="['iot:deviceGroup:remove']"
                      @click.stop=""
                    />
                  </Popconfirm>
                </div>
              </div>
            </template>
          </Tree>
          <!-- 仅本人数据权限 可以考虑直接不显示 -->
          <div v-else class="mt-5">
            <Empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="无数据" />
          </div>
        </div>
      </div>
    </Skeleton>
    <AddGroupModal @reload="loadTree" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.ant-tree) {
  width: 100%;

  .ant-tree-treenode {
    width: 100%;

    .ant-tree-node-content-wrapper {
      flex: 1;
    }
  }
}
</style>
